Router.configure({
  layoutTemplate: 'layout'
});

console.log(4);

TasksListController = RouteController.extend({
  template: 'tasksList',
  pageSize: 5, 
	tasks: function () {
		return this.taskFind(true);
		//return Tasks.find({owner: Meteor.userId()}, {sort: {createdAt: -1}, skip: (this.curPage()-1)*this.pageSize, limit: this.pageSize});
	},
	taskFind: function (isPaging) {
		var cond = {};
		//if (!Session.get("allUser")) {
		//	cond.owner = Meteor.userId();
		//}
        if (Session.get("hideCompleted")) {
	      cond.checked = {$ne: true};
        }
		var ops = {
			sort: {createdAt: -1}
		};
		if (isPaging) {
			ops = _.extend(ops, {
			  skip: (this.curPage()-1)*this.pageSize, 
			  limit: this.pageSize
			});
		}
		return Tasks.find(cond, ops);
	},
    waitOn: function() {
      //this.tasksSub = Meteor.subscribe('tasks');
      return Meteor.subscribe('tasks');
    },
    hideCompleted: function () {
      return Session.get("hideCompleted");
    },
    allUser: function () {
      return Session.get("allUser");
    },
	incompleteCount: function () {
		return Tasks.find({owner: Meteor.userId(), checked: {$ne: true}}).count();
    },
    totalCount: function () {
		return this.taskFind(false).count();
    },
    pages: function () {
    	var pageCount = parseInt((this.totalCount()+this.pageSize-1)/this.pageSize);
    	return pageCount;
    },
    curPage: function() {
    	var tmp = parseInt(this.params.page) || 1;
    	var totalPages = this.pages();
    	if (tmp >= totalPages ) {
    	  tmp = totalPages;
    	}
    	return tmp;
    },
  data: function() {
    console.log('tasks controller data');
    var self = this;
    return {
      tasks: self.tasks(),
      hideCompleted: self.hideCompleted(),
      allUser: self.allUser(),
      incompleteCount: self.incompleteCount(),
      totalCount: self.totalCount(),
      pages: self.pages(),
      curPage: self.curPage()
    };
  }
});

PagingTasksController = TasksListController.extend({
});

Router.route('/', {
	name: 'tasksList',
	controller: PagingTasksController
});

Router.route('/page/:page?', {name: 'pagingTasks'});

Router.route('/tasks/:_id', {
	name: 'taskPage',
  waitOn: function() {
    return Meteor.subscribe('singleTask', this.params._id);
  },
	data: function() { return Tasks.findOne(this.params._id);}
});

Router.route('/tasks/:_id/edit', {
  name: 'taskEdit',
  waitOn: function() {
    return Meteor.subscribe('singleTask', this.params._id);
  },
  data: function() { return Tasks.findOne(this.params._id); }
});
console.log(4.1);

